package com.example.demo.comfig;

import com.example.demo.commom.JsonResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.server.WebSession;
import org.springframework.web.socket.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:龙宝
 * Date:2023-11-18
 * Time:16:55
 */
@Component
public class WebSocketDemo implements WebSocketHandler {
    //保存所有会话信息
    private static final ArrayList<WebSocketSession> sessionList = new ArrayList<>();
    private static final HashMap<WebSocketSession,Integer> userMap = new HashMap<>();




    //全局变量，用户号
    private static int count = 1;
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        if(sessionList.contains(session)) {
            System.out.println("用户" + userMap.get(session) + "连接成功");
        } else {
            System.out.println("用户" + count + "连接成功");
            //存储用户是几号
            userMap.put(session,count);

            //存储用户的session信息
            sessionList.add(session);

            //号数++
            count += 1;
        }


        //向前端告知这是几号用户~
        String message = JsonResult.JsonMessage(1,userMap.get(session) + "号用户");
        session.sendMessage(new TextMessage(message));
        System.out.println(message);
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        System.out.println("收到消息" + message.getPayload().toString());
        //收到消息后，要发送给其他人
        sendMessage(message.getPayload().toString());
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.out.println("连接异常");
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        System.out.println("连接断开");
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
    //向所有用户发送：
    private void sendMessage(String msg) throws IOException {
        for (WebSocketSession session:sessionList) {
            if(session.isOpen()) {
                String message = JsonResult.JsonMessage(0,userMap.get(session) + "号用户：" + msg);
                session.sendMessage(new TextMessage(message));
            }
        }
    }


}
